<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input v-model="isAll" type="checkbox" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
        <tr v-for="(obj, index) in arr" :key="index">
          <td><input v-model="obj.checked" type="checkbox" /></td>
          <td>{{ obj.name }}</td>
          <td>{{ obj.price }}</td>
          <td>
            <button @click="subFn(index)">-</button>
            {{ obj.num }}
            <button @click="addFn(index)">+</button>
          </td>
          <td>{{ obj.price * obj.num }}</td>
          <td><button @click="delFn(index)">删除</button></td>
        </tr>
      </thead>
      <tbody></tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">{{ sum }}</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
export default {
  props: ["arr"],
  computed: {
    isAll: {
      set(val) {
        this.$emit("check", val);
      },
      get() {
        return this.arr.every((obj) => obj.checked === true);
      },
    },
    sum() {
      return this.arr.reduce((sum, obj) => (sum += obj.price * obj.num), 0);
    },
  },
  methods: {
    subFn(index) {
      this.$emit("subNum", index);
    },
    addFn(index) {
      this.$emit("addNum", index);
    },
    delFn(index) {
      this.$emit("delete", index);
    },
  },
};
</script>

<style>
</style>